package cn.czg.cms.controller;

import cn.czg.cms.common.MultipartInputStreamFileResource;
import cn.czg.cms.common.ResultT;
import cn.czg.cms.config.GoFastDfsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
public class FileController {
    private final GoFastDfsProperties goFastDfsProperties;

    public FileController(GoFastDfsProperties goFastDfsProperties) {
        this.goFastDfsProperties = goFastDfsProperties;
    }

    @PostMapping("/api/upload")
    public ResultT<String> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultT.error("文件为空");
        }

        try {
            String fastDfsUrl = goFastDfsProperties.getUploadUrl();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            RestTemplate restTemplate = new RestTemplate();
            String url = restTemplate.postForObject(fastDfsUrl, requestEntity, String.class);
            log.info("触发上传文件成功，url {}", url);
            return ResultT.success(url);
        } catch (Exception e) {
            return ResultT.error("上传失败: " + e.getMessage());
        }
    }

}

